import React, { FC } from 'react'
import { Avatar, IconOftenMt, IconToggle } from '@/pages/manager/components'
import { IconYes, ItemLabelWrap } from './style'
import { useMccStore } from '@/pages/manager/store'
import { ItemData, useSinglePollStore } from './store'
import shallow from 'zustand/shallow'
import { fetchToggleTree } from '@/pages/manager/store.fetch'

export const ListItem: FC<
	ItemData & {
		isCascade: boolean
	}
> = (props) => {
	const { mcc, nestingLevel, isCascade } = props
	const { openMap, tab, chosenMap, selectedKeys, clickSelectItem, itemAddToRight } = useSinglePollStore(
		(state) => ({
			openMap: state.all.openMap,
			tab: state.tab,
			selectedKeys: state.selectedList.map((x) => x.mtKey),
			chosenMap: state[state.tab].chosenMap,
			clickSelectItem: state.clickSelectItem,
			itemAddToRight: state.itemAddToRight,
		}),
		shallow
	)
	const isOpen = openMap[mcc.mtKey]
	const isSelected = chosenMap[mcc.mtKey]
	const isChecked = selectedKeys.includes(mcc.mtKey)
	const isSuperMeeting = useMccStore((state) => state.mccInfo.superMtNum === 1)
	const handleOpenTree = () => {
		if (!mcc.isMt) {
			openMap[mcc.mtKey] = !openMap[mcc.mtKey]
			useSinglePollStore.setState((s) => ({ ...s, all: { ...s.all, openMap } }))
			fetchToggleTree({
				mcc,
				mtKey: mcc.mtKey,
				status: {
					isOpen: openMap[mcc.mtKey],
				},
			})
		}
	}
	const handleClick = (e: React.MouseEvent) => {
		clickSelectItem(mcc, { ctrlKey: e.ctrlKey, shiftKey: e.shiftKey })
	}
	const handleDblClick = () => {
		if (!mcc.isMt && mcc.status.isOnline) {
			handleOpenTree()
		} else if (mcc.isMt) {
			itemAddToRight(mcc)
		}
	}
	return (
		<ItemLabelWrap
			isCascade={isCascade}
			nestingLevel={nestingLevel}
			isOnline={mcc.status.isOnline}
			isVip={mcc.isMt && mcc.status.isVip}
			isSelected={isSelected}
			isMeeting={!mcc.isMt}
			isNameBlue={mcc.status.isManager || mcc.status.isDoubleFlow}
			isAll={tab === 'all'}
			onClick={handleClick}
			onDoubleClick={handleDblClick}
		>
			{isChecked && <IconYes />}
			{!mcc.isMt && mcc.status.isOnline && (
				<IconToggle open={!!isOpen} className="icon-toggle" onClick={handleOpenTree} />
			)}
			<div className="avatar">
				<Avatar value={mcc} />
				{(isSuperMeeting ? mcc.isMt && mcc.status.isInteractive : mcc.isMt && mcc.status.isOftenMt) && (
					<IconOftenMt className="icon-often" />
				)}
			</div>
			{mcc.isMt && mcc.status.isVip && <div className="vip">VIP</div>}
			<div className="name" title={mcc.name}>
				<pre data-mtid={mcc.mtKey}>{mcc.name}</pre>
			</div>
		</ItemLabelWrap>
	)
}
